package com.hp.handler;

import com.hp.enums.ErrorCode;
import com.hp.exception.ServiceException;
import com.hp.response.ServiceResponse;
import com.hp.utils.ResponseGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;


/**
 * 统一异常拦截处理
 * @author hp
 */
@Slf4j
@RestControllerAdvice
public class ServiceControllerAdvice {

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public ServiceResponse handleBusinessException(ServiceException e) {
        log.error(e.getMessage(), e);
        return ResponseGenerator.builder(ErrorCode.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 未定义异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ServiceResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseGenerator.builder(ErrorCode.SYSTEM_ERROR.getCode(), e.getMessage());
    }


    /**
     * 参数校验(Valid)异常，将校验失败的所有异常组合成一条错误信息
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ServiceResponse handleValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("handleValidExceptionHandler: {}", e);

        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 包装绑定异常结果
     *
     */
    private ServiceResponse wrapperBindingResult(BindingResult bindingResult) {
        StringBuilder msg = new StringBuilder();

        for (ObjectError error : bindingResult.getAllErrors()) {
            msg.append(", ");
            if (error instanceof FieldError) {
                msg.append(((FieldError) error).getField()).append(": ");
            }
            msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());

        }
        return ResponseGenerator.builder(ErrorCode.VALID_ERROR.getCode(), msg.substring(2));
    }

    /**
     * Controller上一层相关异常
     *
     */
    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            HttpMediaTypeNotAcceptableException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            // BindException.class,
            // MethodArgumentNotValidException.class
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    @ResponseBody
    public ServiceResponse handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        String code = ErrorCode.SYSTEM_ERROR.getCode();
        String msg = ErrorCode.SYSTEM_ERROR.getDesc();
        return ResponseGenerator.builder(code, msg);
    }
}
